package com.order.shiro;  

import java.util.Collection;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;

import com.order.config.Consts;
import com.order.model.sys.SysUser;
/** 
 * @Title: ShiroDbRealm.java 
 * @Package com.order.shiro 
 * @Description: Realm实现类
 * @author LinBo
 * @date 2014-3-26 下午10:51:45 
 */
public class ShiroDbRealm extends AuthorizingRealm {

	/* 
	* Description: 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用
	*/  
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String userName = ShiroUtils.getUserName();
		if(userName != null){
			// 查询用户授权信息
			Collection<String> roles = SysUser.dao.getRolesNameList(userName);
			if(roles != null && !roles.isEmpty()){
				SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
				info.addRoles(roles);
				return info;
			}
		}
		return null;
	}

	/* 
	* Description: 认证回调函数,登录时调用
	*/  
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String userName = token.getUsername();
		String password = String.valueOf(token.getPassword());
		String sql = "select u.id, u.name, u.password "
				+ " from sys_user u "
				+ " where u.name = ? "
				+ " and u.password = ? ";
		SysUser user = SysUser.dao.findFirst(sql, userName, password);
		if(user != null){
			return returnSimpleAuthen(user, password);
		}
		return null;
	}

	/*
	 * 更新用户授权信息缓存
	 */
	protected void clearCachedAuthorizationInfo(String principal) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
		clearCachedAuthorizationInfo(principals);
	}

	/*
	 * 清除所有用户授权信息缓存
	 */
	protected void clearAllCachedAuthorizationInfo() {
		Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
		if (cache != null) {
			for (Object key : cache.keys()) {
				cache.remove(key);
			}
		}

	}


	public AuthenticationInfo returnSimpleAuthen(SysUser user,String password){
		Subject subject=SecurityUtils.getSubject(); 
		subject.getSession().setAttribute(Consts.USER_SESSION, user);
		ShiroPrincipal principal = new ShiroPrincipal(user);
		return new SimpleAuthenticationInfo(principal, password, getName());	
	}
}
  